package com.kaifamiao.wendao.controller;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.service.CustomerService;
import com.kaifamiao.wendao.utils.Constants;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/customer/*")
public class CustomerServlet extends HttpServlet {

    private CustomerService customerService;
    private String ctxPath;

    @Override
    public void init() throws ServletException {
        customerService = new CustomerService();
        ctxPath = this.getServletContext().getContextPath();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String method = request.getMethod();
        String uri = request.getRequestURI();
        // GET "/customer/sign/up"
        if("GET".equals(method) && uri.endsWith("/sign/up")) {
            this.signUpPage(request, response);
            return;
        }
        // POST "/customer/sign/up"
        if("POST".equals(method) && uri.endsWith("/sign/up")) {
            this.signUpAction(request, response);
            return;
        }
        // GET "/customer/sign/in"
        if("GET".equals(method) && uri.endsWith("/sign/in")) {
            this.signInPage(request, response);
            return;
        }
        //POST "/customer/sign/in"
        if("POST".equals(method) && uri.endsWith("/sign/in")){
            this.signInAction(request,response);
            return;
        }
        // GET "/customer/sign/out"
        if("GET".equals(method) && uri.endsWith("/sign/out")) {
            this.signOutAction(request, response);
            return;
        }

        //修改用户信息
        //GET /customer/edit
        if("GET".equals(method) && uri.endsWith("/edit")){
            this.editPage(request,response);
            return;
        }
        //POST /customer/edit
        if("POST".equals(method) && uri.endsWith("/edit")){
            this.editAction(request,response);
            return;
        }

        //修改密码
        //GET /customer/change
        if("GET".equals(method) && uri.endsWith("/change")){
            this.changePage(request,response);
            return;
        }
        //POST /customer/change
        if("POST".equals(method) && uri.endsWith("/change")){
            this.changeAction(request,response);
            return;
        }
    }
    //GET /customer/change
    private void changePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Long cid = Long.valueOf(id);
        Customer c = customerService.find(cid);
        request.setAttribute("customer",c);
        String path = "/WEB-INF/pages/customer/change.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(path);
        dispatcher.forward(request,response);

    }

    //POST /customer/change
    private void changeAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        Customer c = (Customer) request.getAttribute("customer");

        if(StringUtils.isEmpty(id)){
            HttpSession session = request.getSession();
            session.setAttribute("message","用户id为空");
            response.sendRedirect(ctxPath+"/customer/list");
        }

        if(validateChange(request)){
            String password = request.getParameter("password");
            String encrypted = customerService.encrypt(password, c.getSalt());
            c.setPassword(encrypted);
            customerService.update(c);
            response.sendRedirect(ctxPath + "/customer/list");
            return;
        }
        response.sendRedirect(ctxPath+"/customer/change?id="+id);

    }

    private boolean validateChange(HttpServletRequest request) {
        String id = request.getParameter("id");
        String original = request.getParameter("original");
        String password = request.getParameter("password");
        String confirm = request.getParameter("confirm");
        HttpSession session = request.getSession();
        if(StringUtils.isEmpty(original) || StringUtils.isBlank(original)) {
            session.setAttribute("message", "必须输入原始密码");
            return false;
        }

        if(StringUtils.isEmpty(password) || StringUtils.isBlank(password)) {
            session.setAttribute("message", "请输入新密码");
            return false;
        }

        if( !StringUtils.equals(password,confirm) ) {
            session.setAttribute("message", "两次输入的新密码不一致");
            return false;
        }

        Customer c = customerService.find(Long.valueOf(id));
        request.setAttribute("targetCustomer", c );
        // 对用户输入的原始密码进行加密
        String encrypted = customerService.encrypt(original, c.getSalt());
        // 对用户输入的原始密码加密后再与数据库中存储的密码比较
        if( !StringUtils.equals(encrypted, c.getPassword())) {
            session.setAttribute("message", "你输入的原始密码不正确");
            return false;
        }

        return true;

    }



    //GET /customer/edit
    private void editPage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
       // Customer c = (Customer) request.getAttribute(Constants.CUSTOMER_LOGINED);

        String id = request.getParameter("id");
        if(StringUtils.isEmpty(id) || StringUtils.isBlank(id)){
            response.sendRedirect(ctxPath+"/topic/list");
            return;
        }
        Long oid = Long.valueOf(id);
        Customer c = customerService.find(oid);
        request.setAttribute("customer",c);
        String path = "/WEB-INF/pages/customer/edit.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(path);
        dispatcher.forward(request,response);
    }

    //POST /customer/edit
    private void editAction(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {String id = request.getParameter("id");
        String nickname = request.getParameter("nickname");
        if(validateEdit(request)){
            Long oid = Long.valueOf(id);
            Customer c = customerService.find(oid);
            c.setNickname(nickname);
            customerService.update(c);
//            HttpSession session = request.getSession();
//            session.setAttribute("message","修改成功");
            response.sendRedirect(ctxPath+"/topic/list");
            return;
        }
        response.sendRedirect(ctxPath+"/customer/edit?id="+id);
    }

    private boolean validateEdit(HttpServletRequest request) {
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String nickname = request.getParameter("nickname");
        if(StringUtils.isBlank(nickname) || StringUtils.isEmpty(nickname)){
            HttpSession session = request.getSession();
            session.setAttribute("id",id);
            session.setAttribute("username",username);
            session.setAttribute("message","昵称不能为空");
            return  false;
        }
        return true;
    }



    // GET "/customer/sign/up"
    protected void signUpPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = "/WEB-INF/pages/customer/sign-up.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(path);
        dispatcher.forward(request, response);
    }

    private boolean validateSignUp(HttpServletRequest request)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String nickname = request.getParameter("nickname");
        String password = request.getParameter("password");
        String confirm = request.getParameter("confirm");
        String captcha = request.getParameter("captcha");

        HttpSession session = request.getSession();

        // 检查用户名是否为空
        if(StringUtils.isEmpty(username) || StringUtils.isBlank(username)){
            session.setAttribute("message","用户名不能为空");
            return false;
        }

        // 检查密码是否为空
        if(StringUtils.isEmpty(password) || StringUtils.isBlank(password)){
            session.setAttribute("message","密码不能为空");
            return false;
        }

        // 检查两次输入密码是否一致
        if(!StringUtils.equals(confirm,password)){
            session.setAttribute("message","两次输入密码不一致");
            return false;
        }

        // 检查验证码与会话中存储的CAPTCHA属性值是否相等
        //获取会话中的CAPTCHA属性值
        String cap = (String) session.getAttribute("CAPTCHA");
        if(!StringUtils.equalsIgnoreCase(cap,captcha)){
            session.setAttribute("message","验证码输入错误");
            return false;
        }

        // 检查用户名是否被占用(需要去数据库检查)
        //结果为true则说明是已经占用
        boolean result = customerService.findUname(username);
        if(result){
            session.setAttribute("message","用户名已经存在");
            return false;
        }

        return true;
    }

    // POST "/customer/sign/up"
    protected void signUpAction(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if(this.validateSignUp(request)){
            Customer c = new Customer();
            try {
                BeanUtils.populate(c,request.getParameterMap());
            } catch (Exception e) {
                e.printStackTrace();
            }
            customerService.save(c);
            HttpSession session = request.getSession();
            session.setAttribute("message", "注册成功");
            response.sendRedirect(request.getContextPath() + "/customer/sign/in" );
            return;
        }
        response.sendRedirect(request.getContextPath() + "/customer/sign/up" );
    }

    // GET "/customer/sign/in"
    protected void signInPage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = "/WEB-INF/pages/customer/sign-in.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(path);
        dispatcher.forward(request, response);
    }
    // POST "/customer/sign/in"
    private void signInAction(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        HttpSession session = request.getSession();
        String username = request.getParameter("username");
        Customer c = customerService.find(username);

        if(!StringUtils.equals(username,c.getUsername())){
            session.setAttribute("message","用户名不正确");
            response.sendRedirect(request.getContextPath() + "/customer/sign/in");
            return;
        }
        //获得数据库密码
        String dbpass = c.getPassword();
        //获得输入框输入的密码
        String password = request.getParameter("password");

        String jiami = customerService.encrypt(password,c.getSalt());

        if(!StringUtils.equals(dbpass,jiami)){
            session.setAttribute("username",username);
            session.setAttribute("message","用户密码不正确");
            response.sendRedirect(request.getContextPath() + "/customer/sign/in");
        }

        String captcha = request.getParameter("captcha");
        // 检查验证码与会话中存储的CAPTCHA属性值是否相等
        //获取会话中的CAPTCHA属性值
        String cap = (String) session.getAttribute("CAPTCHA");
        if(!StringUtils.equalsIgnoreCase(cap,captcha)){
            session.setAttribute("message","验证码输入错误");
            response.sendRedirect(request.getContextPath() + "/customer/sign/in");
        }

        session.setAttribute("customer",c);
        response.sendRedirect(request.getContextPath() + "/index.jsp");


    }

    // GET "/customer/sign/out"
    protected void signOutAction(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("customer");
        response.sendRedirect(request.getContextPath() + "/index.jsp");
    }

}
